/**
 * Administrator
 * 2011-3-9
 * TODO
 */
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**南方航空
 * @author 0707
 * @date 2011-3-9
 * @description TODO
 */
public class GetFlightListCZ {

	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();

			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "ec.csair.com");
		    header.put("Referer", "http://ec.csair.com/B2C/modules/order/simple/showflights.jsp");
            header.put("X-Requested-With","XMLHttpRequest");
			//使用get请求，赋值参数
            StringBuffer  urlStringBuffer =  new StringBuffer();
            String date  = queryInfo.getDateString().replace("-","");
            urlStringBuffer.append("http://ec.csair.com/B2C/detail-1-S");
            //http://ec.csair.com/B2C/detail-1-S-0-1-CAN-SHA-20110311-1.dat
            ///detail-1-S"+"-"+cabinOrder+"-"+isDirect+"-"+citys[i]+"-"+citys[i+1]+"-"+tempdate+"-"+isIet+".dat";
            urlStringBuffer.append("-0-1-");   //cabinOrder  品牌类型   isDirect是否直达
            urlStringBuffer.append(queryInfo.getOrgCity()+"-"+queryInfo.getDesCity());  //出发城市、到达城市
            urlStringBuffer.append("-"+date+"-1.dat");   //tempdate 出发日期；isIet 是否含国外航班
           
            try {
	        	//返回的HTML
				responseText = proxy.doRequest(
             	urlStringBuffer.toString(), null, header,"UTF-8");
				 //System.out.println(responseText);
				resultInfo = (ResultInfo)analyzeResopnseText(responseText);
	 
			}catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
	        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
	
	          	return resultInfo;
			 
		}
		
		
		/**
		 * 根据山东航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
			 
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象
         
		      if (source==null||source.trim().length()==0) {
				return null;
			}
	 	 
		      DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
 try {
	          DocumentBuilder dombuilder=domfac.newDocumentBuilder();
	          InputStream is = new ByteArrayInputStream(source.getBytes());  //将XML的String转换为Inputstream
	          Document doc=dombuilder.parse(is);
	          Element root=doc.getDocumentElement();
	          NodeList flights=root.getElementsByTagName("FLIGHT");
	           if (flights.getLength()==0) {                           //没有数据，直接返回
				System.out.println("南方航空没有查询到对应的航班信息");
				return resultInfo;
			}
	           ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
	           for(int i=0;i<flights.getLength();i++){
	        	  FlightInfo tempInfo = new FlightInfo();
	        	  Element flight = (Element)flights.item(i);
	      
	        	  boolean codeShare = false;
	        	  String departTime = "";
	        	  String arriveTime = "";
	        	  int stopNum = 0;
	        		 
	         
                 	//航班号
                    tempInfo.setFlightNo(flight.getElementsByTagName("FLIGHTNO").item(0).getFirstChild().getNodeValue().trim());
					//为代码共享航班
					if (Boolean.parseBoolean(flight.getElementsByTagName("CODESHARE").item(0).getFirstChild().getNodeValue())) {
						tempInfo.setShareCodeFlag(true);
					}
					departTime = flight.getElementsByTagName("DEPTIME").item(0).getFirstChild().getNodeValue().trim();  //转换时间格式
					arriveTime = flight.getElementsByTagName("ARRTIME").item(0).getFirstChild().getNodeValue().trim();
					departTime = departTime.substring(0, 2)+":"+departTime.substring(2,4);
					arriveTime = arriveTime.substring(0, 2)+":"+arriveTime.substring(2,4);
					
					tempInfo.setTakeOffTime(departTime);
					tempInfo.setArriveTime(arriveTime);
					//机型
					tempInfo.setPlaneType(flight.getElementsByTagName("PLANE").item(0).getFirstChild().getNodeValue().trim());
					//经停
					stopNum = Integer.parseInt(flight.getElementsByTagName("STOPNUMBER").item(0).getFirstChild().getNodeValue().trim());
					if (stopNum>0) {
					tempInfo.setStopOver(true);	
					}
					//获得舱位、价格
					NodeList cabins = flight.getElementsByTagName("CABIN");
					priceList = new ArrayList();
			    	 double tempMinPrice = 0.0;
			    	 double tempMaxPrice = 0.0;
			    	 boolean isFirst = true;
					 for (int j = 0; j < cabins.getLength(); j++) {
						String cabinNO = "";
						Element cabin = (Element)cabins.item(j);
						NodeList priceNodeList = cabin.getElementsByTagName("ADULTPRICE");
						if (priceNodeList==null||priceNodeList.getLength()==0) {   //如果没有该舱位的价格信息
                              continue ;
						}
						priceInfo = new PriceInfo();
						NodeList cabinList = cabin.getElementsByTagName("NAME");  
						priceInfo.setSpace(cabinList.item(0).getFirstChild().getNodeValue());    //舱位
						priceInfo.setPrice(Double.parseDouble(priceNodeList.item(0).getFirstChild().getNodeValue()));
						priceList.add(priceInfo);
				    	  //一个航班不同cabin的最低和最高价格获取
				    	  if (isFirst) {
				    		  tempMinPrice = priceInfo.getPrice();
				    		  tempMaxPrice = priceInfo.getPrice();
				    		  tempInfo.setMinprice(tempMinPrice);
				    		  tempInfo.setMaxprice(tempMaxPrice);
				    		  isFirst = false;
						}
				    	 
						     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
						    	 tempMinPrice = priceInfo.getPrice();
								}
						     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
						    	 tempMaxPrice = priceInfo.getPrice(); 
							}
						     tempInfo.setMaxprice(tempMaxPrice);
						     tempInfo.setMinprice(tempMinPrice);
					}
				  tempInfo.setPrice(priceList);
	        	  flightInfos.add(tempInfo);
	        	  
				     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
				     if (tempIsFirstForAll) {      //初始值
				    	 tempMinPriceForAll = tempInfo.getMinprice();
				    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				    	 tempIsFirstForAll  = false;
					}
				     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
	 
				    	 tempMinPriceForAll = tempInfo.getMinprice();
					}
				     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
					 
				    	 tempMaxPriceForAll = tempInfo.getMaxprice();
					}
			    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
			    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
				     
	           }
                 resultInfo.setResultList(flightInfos);

} catch (Exception e) {
	e.printStackTrace();
}
		      
		      
			return resultInfo;
		}


}
